package com.jnc.web.biz.system.controller;

import com.jnc.common.base.BaseResp;
import com.jnc.common.constant.SysConstant;
import com.jnc.common.exception.BaseException;
import com.jnc.core.base.controller.BaseController;
import com.jnc.core.base.model.Role;
import com.jnc.core.base.model.User;
import com.jnc.core.base.service.RoleService;
import com.jnc.core.base.service.UserService;
import com.jnc.core.config.shiro.util.ShiroUtil;
import com.jnc.core.web.page.TableResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: jjn
 * @Date: 2018/9/18
 * @Desc:
 */
@Slf4j
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 初始化展示页面
     * @return
     */
    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String init(){
        return prefix + "/list";
    }

    /**
     * 初始化新增页面
     * @param model
     * @return
     */
    @GetMapping("/addInit")
    public String addInit(ModelMap model){
        model.put("roleList", roleService.queryRole(new Role()));
        return prefix + "/add";
    }

    /**
     * 初始化编辑页面
     * @param userId
     * @param model
     * @return
     */
    @GetMapping("/editInit/{userId}")
    public String editInit(@PathVariable("userId") Integer userId, ModelMap model){
        model.put("info", userService.getUser(userId));
        model.put("roleList", roleService.queryRole(new Role()));
        return prefix + "/edit";
    }

    /**
     * 初始化修改密码页面
     * @return
     */
    @GetMapping("/editPWInit")
    public String editPWInit(){
        return prefix + "/password";
    }

    /**
     * 查询列表数据
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableResult list(User user){
        log.debug("UserController.list.user : {}", user);
        initPage();
        List<User> list = userService.queryUser(user);
        return getTableData(list);
    }

    /**
     * 新增
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:add")
    @PostMapping("/add")
    @ResponseBody
    public BaseResp add(@RequestBody User user){
        log.debug("UserController.add.user : {}", user);
        //校验登录账号是否已存在
        List<User> list = userService.checkUser(user);
        if(list != null && list.size() > 0){
            return error("该登录账号已存在");
        }
        //默认状态正常
        user.setStatus(SysConstant.STATUS_CODE_OK);
        //密码加密
        user.setPassword(ShiroUtil.md5(user.getPassword(), user.getLoginName()));
        return toAjax(userService.addUser(user));
    }

    /**
     * 编辑
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:edit")
    @PostMapping("/edit")
    @ResponseBody
    public BaseResp edit(@RequestBody User user){
        log.debug("UserController.edit.user : {}", user);
        //校验登录账号是否已存在
        List<User> list = userService.checkUser(user);
        if(list != null && list.size() > 0){
            return error("该登录账号已存在");
        }
        return toAjax(userService.editUser(user));
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @RequiresPermissions("system:user:remove")
    @PostMapping("/remove")
    @ResponseBody
    public BaseResp remove(@RequestParam String ids){
        return toAjax(userService.deleteUser(ids));
    }


    @PostMapping("/editPW")
    @ResponseBody
    public BaseResp editPW(@RequestBody User user){
        log.debug("UserController.editPW.user : {}", user);
        //获取当前用户
        User dto = ShiroUtil.getUser();
        //校验原密码是否输入正确
        if(dto != null){
            //密码MD5加密，跟shiro同步，校验原始密码是否一致
            String md5Password = ShiroUtil.md5(user.getPassword(), dto.getLoginName());
            if(!StringUtils.equals(md5Password,dto.getPassword())){
                throw new BaseException("原密码错误!");
            }
        }
        //4、密码MD5加密，跟shiro同步，加密新密码
        String md5NewPassword = ShiroUtil.md5(user.getNewPassword(), dto.getLoginName());
        //3、密码修改
        dto.setNewPassword(md5NewPassword);
        return toAjax(userService.editPW(dto));
    }
}
